<template>
    <div style="border: 1px solid #ccc;">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig" :mode="mode"
            @onCreated="onCreated" />
    </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css';
import { Boot } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
// editor为空获取value值存在"<p><br></p>"，在表单中无法校验，借助于插件解决
function withEmptyHtml(editor) {
    const { getHtml } = editor
    const newEditor = editor

    newEditor.getHtml = () => {
        if (newEditor.isEmpty()) {
            return ''
        }
        return getHtml()
    }

    return newEditor
}
// 注册插件
Boot.registerPlugin(withEmptyHtml);
export default {
    components: { Editor, Toolbar },
    model: {
        prop: 'value',
        event: 'change',
    },
    props: {
        value: {
            type: String,
            default: '',
        }
    },
    watch: {
        value(newValue, oldValue) {
            this.html = newValue;
        },
        html(newValue, oldValue) {
            this.$emit('change', newValue)
        }
    },
    data() {
        return {
            editor: null,
            toolbarConfig: {},
            html: '',
            editorConfig: {
                placeholder: '请输入内容...',
                MENU_CONF: {
                    uploadImage: {
                        server: 'http://localhost:3001/upload/editor/',
                        fieldName: 'file',
                        headers: { Authorization: `Bearer ${sessionStorage.access_token}` },
                    }
                }
            },
            mode: 'default',
        }
    },
    methods: {
        onCreated(editor) {
            this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
        },
    },
    beforeDestroy() {
        const editor = this.editor
        if (editor == null) return
        editor.destroy() // 组件销毁时，及时销毁编辑器
    }
}
</script>